<template>
  <v-dialog v-model="dialog" max-width="600px">
    <v-card>
      <v-card-title>
        <span class="text-h5">{{ role?.id ? '编辑角色' : '新建角色' }}</span>
      </v-card-title>

      <v-card-text>
        <v-form ref="form" v-model="valid">
          <v-text-field
            v-model="formData.name"
            label="角色名"
            :rules="[(v) => !!v || '角色名不能为空']"
            required
          />
          <v-text-field v-model="formData.description" label="角色描述" />
          <v-select
            v-model="formData.tagIds"
            :items="tags"
            item-title="name"
            item-value="id"
            label="标签权限"
            multiple
            chips
            :rules="[(v) => v.length > 0 || '请至少选择一个标签']"
          />
        </v-form>
      </v-card-text>

      <v-card-actions>
        <v-spacer />
        <v-btn color="primary" variant="text" @click="close">取消</v-btn>
        <v-btn color="primary" variant="text" @click="save" :disabled="!valid">保存</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { getTags } from '@/api/tags'

const props = defineProps({
  modelValue: Boolean,
  role: Object,
})
const emit = defineEmits(['update:modelValue', 'submit'])

const dialog = ref(false)
const valid = ref(false)
const form = ref(null)
const tags = ref([])

const formData = ref({
  id: '',
  name: '',
  description: '',
  tagIds: [],
})

watch(
  () => props.modelValue,
  (val) => {
    dialog.value = val
    if (val) initForm()
  },
)
watch(
  () => dialog.value,
  (val) => {
    emit('update:modelValue', val)
    if (!val) resetForm()
  },
)

const initForm = async () => {
  const res = await getTags()
  tags.value = res.data
  if (props.role) {
    formData.value = {
      id: props.role.id,
      name: props.role.name,
      description: props.role.description,
      tagIds: props.role.tagIds || [],
    }
  }
}

const resetForm = () => {
  formData.value = {
    id: '',
    name: '',
    description: '',
    tagIds: [],
  }
  form.value?.resetValidation()
}

const close = () => {
  dialog.value = false
}

const save = () => {
  form.value.validate().then((success) => {
    if (success) {
      emit('submit', formData.value)
      close()
      resetForm()
    }
  })
}

onMounted(() => {
  initForm()
})
</script>
